package com.ruoyi.pack.service.impl;

import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.pack.domain.PackProjectMaterial;
import com.ruoyi.pack.mapper.PackProjectMaterialMapper;
import com.ruoyi.pack.service.IPackProjectMaterialService;

/**
 * 项目物料Service业务层处理
 * 
 * @author ruoyi
 */
@Service
public class PackProjectMaterialServiceImpl implements IPackProjectMaterialService 
{
    private static final Logger log = LoggerFactory.getLogger(PackProjectMaterialServiceImpl.class);

    @Autowired
    private PackProjectMaterialMapper packProjectMaterialMapper;

    /**
     * 查询项目物料
     * 
     * @param projectMaterialId 项目物料主键
     * @return 项目物料
     */
    @Override
    public PackProjectMaterial selectPackProjectMaterialByProjectMaterialId(Long projectMaterialId)
    {
        return packProjectMaterialMapper.selectPackProjectMaterialByProjectMaterialId(projectMaterialId);
    }

    /**
     * 查询项目物料列表
     * 
     * @param packProjectMaterial 项目物料
     * @return 项目物料
     */
    @Override
    public List<PackProjectMaterial> selectPackProjectMaterialList(PackProjectMaterial packProjectMaterial)
    {
        return packProjectMaterialMapper.selectPackProjectMaterialList(packProjectMaterial);
    }

    /**
     * 查询项目物料列表（用于导出）
     * 
     * @param packProjectMaterial 项目物料
     * @return 项目物料
     */
    @Override
    public List<PackProjectMaterial> selectPackProjectMaterialListForExport(PackProjectMaterial packProjectMaterial)
    {
        return packProjectMaterialMapper.selectPackProjectMaterialListForExport(packProjectMaterial);
    }

    /**
     * 新增项目物料
     * 
     * @param packProjectMaterial 项目物料
     * @return 结果
     */
    @Override
    @Transactional
    public int insertPackProjectMaterial(PackProjectMaterial packProjectMaterial)
    {
        // 校验物料编码唯一性
        if (checkMaterialCodeUnique(packProjectMaterial).equals("1"))
        {
            throw new ServiceException("新增项目物料'" + packProjectMaterial.getMaterialName() + "'失败，物料编码已存在");
        }
        
        packProjectMaterial.setCreateTime(DateUtils.getNowDate());
        return packProjectMaterialMapper.insertPackProjectMaterial(packProjectMaterial);
    }

    /**
     * 修改项目物料
     * 
     * @param packProjectMaterial 项目物料
     * @return 结果
     */
    @Override
    @Transactional
    public int updatePackProjectMaterial(PackProjectMaterial packProjectMaterial)
    {
        // 校验物料编码唯一性
        if (checkMaterialCodeUnique(packProjectMaterial).equals("1"))
        {
            throw new ServiceException("修改项目物料'" + packProjectMaterial.getMaterialName() + "'失败，物料编码已存在");
        }
        
        packProjectMaterial.setUpdateTime(DateUtils.getNowDate());
        return packProjectMaterialMapper.updatePackProjectMaterial(packProjectMaterial);
    }

    /**
     * 批量删除项目物料
     * 
     * @param projectMaterialIds 需要删除的项目物料主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deletePackProjectMaterialByProjectMaterialIds(Long[] projectMaterialIds)
    {
        return packProjectMaterialMapper.deletePackProjectMaterialByProjectMaterialIds(projectMaterialIds);
    }

    /**
     * 删除项目物料信息
     * 
     * @param projectMaterialId 项目物料主键
     * @return 结果
     */
    @Override
    public int deletePackProjectMaterialByProjectMaterialId(Long projectMaterialId)
    {
        return packProjectMaterialMapper.deletePackProjectMaterialByProjectMaterialId(projectMaterialId);
    }

    /**
     * 根据项目ID查询项目物料列表
     * 
     * @param projectId 项目ID
     * @return 项目物料集合
     */
    @Override
    public List<PackProjectMaterial> selectPackProjectMaterialByProjectId(Long projectId)
    {
        return packProjectMaterialMapper.selectPackProjectMaterialByProjectId(projectId);
    }

    /**
     * 根据项目ID删除项目物料
     * 
     * @param projectId 项目ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deletePackProjectMaterialByProjectId(Long projectId)
    {
        return packProjectMaterialMapper.deletePackProjectMaterialByProjectId(projectId);
    }

    /**
     * 校验项目下物料编码是否唯一
     * 
     * @param packProjectMaterial 项目物料信息
     * @return 结果
     */
    @Override
    public String checkMaterialCodeUnique(PackProjectMaterial packProjectMaterial)
    {
        Long projectMaterialId = StringUtils.isNull(packProjectMaterial.getProjectMaterialId()) ? -1L : packProjectMaterial.getProjectMaterialId();
        PackProjectMaterial info = packProjectMaterialMapper.checkMaterialCodeUnique(packProjectMaterial.getProjectId(), packProjectMaterial.getMaterialCode());
        if (StringUtils.isNotNull(info) && info.getProjectMaterialId().longValue() != projectMaterialId.longValue())
        {
            return "1";
        }
        return "0";
    }

    /**
     * 根据物料编码查询项目物料
     * 
     * @param materialCode 物料编码
     * @return 项目物料列表
     */
    @Override
    public List<PackProjectMaterial> selectPackProjectMaterialByMaterialCode(String materialCode)
    {
        return packProjectMaterialMapper.selectPackProjectMaterialByMaterialCode(materialCode);
    }

    /**
     * 导入项目物料数据
     * 
     * @param materialList 项目物料数据列表
     * @param isUpdateSupport 是否支持更新，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public String importProjectMaterial(List<PackProjectMaterial> materialList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(materialList) || materialList.size() == 0)
        {
            throw new ServiceException("导入项目物料数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        
        for (PackProjectMaterial material : materialList)
        {
            try
            {
                // 验证是否存在这个物料
                PackProjectMaterial m = packProjectMaterialMapper.checkMaterialCodeUnique(material.getProjectId(), material.getMaterialCode());
                if (StringUtils.isNull(m))
                {
                    material.setCreateBy(operName);
                    this.insertPackProjectMaterial(material);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、物料 " + material.getMaterialName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    material.setProjectMaterialId(m.getProjectMaterialId());
                    material.setUpdateBy(operName);
                    this.updatePackProjectMaterial(material);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、物料 " + material.getMaterialName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、物料 " + material.getMaterialName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、物料 " + material.getMaterialName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 批量新增项目物料
     * 
     * @param projectId 项目ID
     * @param materialList 项目物料列表
     * @return 结果
     */
    @Override
    @Transactional
    public int batchInsertProjectMaterial(Long projectId, List<PackProjectMaterial> materialList)
    {
        if (StringUtils.isNull(materialList) || materialList.size() == 0)
        {
            throw new ServiceException("批量新增项目物料数据不能为空！");
        }
        
        int count = 0;
        for (PackProjectMaterial material : materialList)
        {
            material.setProjectId(projectId);
            material.setCreateTime(DateUtils.getNowDate());
            count += packProjectMaterialMapper.insertPackProjectMaterial(material);
        }
        return count;
    }
} 